/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import Data.Category;
import Data.Event;
import Data.Member;
import Data.Subcriber;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author NGOCLINH-PC
 */
public class EventPR extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    private final String UPLOAD_DIRECTORY = "C:\\Users\\TrongChien\\Desktop\\nlpp263\\prj\\nlpp\\web\\uploads";
    String fullnameimage = "";

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        //MultipartRequest mul = new MultipartRequest(request, ".", 10 * 1024 * 1024, "UTF-8");
        try {
            if (request.getParameter("txtSearch") != null || request.getParameter("listmenuloc") != null) {

                String name = request.getParameter("txtSearch");
                if (name != "" || Integer.parseInt(request.getParameter("listmenuloc")) != 1) {
                    //String name = request.getParameter("txtSearch");
                    int cateid = Integer.parseInt(request.getParameter("listmenuloc"));
                    ArrayList<Event> arrEven = Event.ESelectBySearch(" AND EventName like('%" + name + "%') and CategoryID = " + cateid + " ");
                    Event f = new Event();
                    f.setArrEvent(arrEven);

                } else if (Integer.parseInt(request.getParameter("listmenuloc")) == 1) {
                    ArrayList<Event> arrEven = Event.ESelectBySearch(" ");
                    Event f = new Event();
                    f.setArrEvent(arrEven);
                }
                HttpSession Session = request.getSession();
                Session.setAttribute("sstimkiem", "a");
            }
            //////////

            if (request.getParameter("AeventID") != null) {
                int idpay = Integer.parseInt(request.getParameter("AeventID"));
                try {
                    Event.Edelete(idpay);
                } catch (Exception exc) {
                    exc.fillInStackTrace();
                }
            } else {//if (request.getParameter("insot") != null)
                Date now = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String date = sdf.format(now.getTime());
                int Category = 0;
                String eventname = null;
                String speaker = null;
                String address = null;
                String description = null;
                String content = null;
                float price = 0;
                String timeevent = null;
                String deadline = null;

                int stt = 0;
                //
                if (ServletFileUpload.isMultipartContent(request)) {
                    try {

                        List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
                        for (FileItem item : multiparts) {
                            if (!item.isFormField()) {
                                String name = new File(item.getName()).getName();
                                item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
                                fullnameimage = name;
                            } else {

                                if (item.getFieldName().equals("txtCategory")) {
                                    Category = Integer.parseInt(item.getString());
                                }
                                if (item.getFieldName().equals("txtEventname")) {
                                    eventname = item.getString();
                                }
                                if (item.getFieldName().equals("txtSpeakers")) {
                                    speaker = item.getString();
                                }
                                if (item.getFieldName().equals("txtAddress")) {
                                    address = item.getString();
                                }
                                if (item.getFieldName().equals("txtDescription")) {
                                    description = item.getString();
                                }
                                if (item.getFieldName().equals("txtContent")) {
                                    content = item.getString();
                                }
                                if (item.getFieldName().equals("txtPrice")) {
                                    price = Float.parseFloat(item.getString());
                                }
                                if (item.getFieldName().equals("txtTimeEvent")) {
                                    timeevent = item.getString();
                                }
                                if (item.getFieldName().equals("txtDeadline")) {
                                    deadline = item.getString();
                                }
                                if (item.getFieldName().equals("radio1")) {
                                    stt = Integer.parseInt(item.getString());
                                }
                            }
                        }
                        Event.Einsert(eventname, speaker, address, description, content, price, date, timeevent, deadline, fullnameimage, stt, Category);
                        /// send mail
                        Subcriber ct = new Subcriber();
                        ArrayList<Subcriber> a = ct.SselectbyCID(Category);
                        if (a.size() > 0) {
                            for (int i = 0; i < a.size(); i++) {
                                Subcriber pay = a.get(i);
                                int memid = pay.getMemberID();
                                ///
                                Member mem = new Member();
                                ArrayList<Member> am = mem.MselectById(memid);
                                if (am.size() > 0) {
                                    for (int j = 0; j < am.size(); j++) {
                                        Member paym = am.get(j);

                                        Category cte = new Category();
                                        ArrayList<Category> aca = cte.CselectById(pay.getCategoryID());
                                        if (aca.size() > 0) {
                                            for (int k = 0; k < aca.size(); k++) {
                                                Category categ = aca.get(k);
                                                String email = paym.getEmail();
                                                String subject = "Message that event new  from KSC";
                                                String msg = "Dear " + paym.getMemberName() + "\n"
                                                        + "KSC is going too held a new event on " + timeevent + " On the event list " + categ.getCategoryName() + "  that you have registered from KSC. to receive information from KSC in details, http://localhost:8084/nlpp/client/index.jsp?page=listEvent \n"
                                                        + "Best Regards,\n"
                                                        + "KSC";
                                                Event.send(email, subject, msg, "t1106k.nnlinh@aptech.vn", "ngoclinh113");
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } catch (Exception ex) {
                        //request.setAttribute("message", "File Upload Failed due to " + ex);
                    }
                }
            }
            response.sendRedirect("/nlpp/admin/index.jsp?page=Event");

        } finally {
            out.close();
        }
    }
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">

    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
